package middleware

import (
	"GoAdmin/common"
	"GoAdmin/service"
	"fmt"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

// Authorize 拦截器
func Authorize() gin.HandlerFunc {

	return func(c *gin.Context) {
		e := service.Enforcer
		//从DB加载策略
		err := e.LoadPolicy()
		if err != nil {
			log.Println(err)
			return
		}

		//获取请求的URI
		obj := c.Request.URL.RequestURI()
		//获取请求方法
		act := c.Request.Method
		//获取用户的角色
		// user := c.Request.PostFormValue("user")
		user, ok := common.GetCtxUser(c)
		if !ok {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "无权限访问"})
			c.Abort()
		}
		sub := user.Name
		//判断策略中是否存在

		if ok, err := e.Enforce(sub, obj, act); ok {
			fmt.Println(obj, "权限验证通过")
			c.Next()
		} else {
			fmt.Println(obj, "权限验证没有通过", err)
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "无权限访问"})
			c.Abort()
		}
	}
}
